package org.zachary.agent.infrastructure.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import org.springframework.data.redis.serializer.RedisSerializer;
import java.nio.charset.StandardCharsets;

public class FastJson2RedisSerializer<T> implements RedisSerializer<T> {
    private final Class<T> clazz;

    public FastJson2RedisSerializer(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T object) {
        if (object == null) return new byte[0];
        // 启用Java 21 Record支持，关闭类型信息（安全优化）
        return JSON.toJSONString(object, JSONWriter.Feature.WriteClassName).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public T deserialize(byte[] bytes) {
        if (bytes == null || bytes.length == 0) return null;
        String json = new String(bytes, StandardCharsets.UTF_8);
        // 支持Java 21 Record反序列化
        return JSON.parseObject(json, clazz);
    }
}
